/**
 * @file
 * @auth jinguangguo
 * @date 2017/09/08
 */

import Vue from 'vue';

import filter from '../../../grsc-base/util/filter';
import Validator from '../../../grsc-base/component/Validator/main';
import commonService from '../../common/commonService';
import commonUtil from '../../common/util';
import service from './service';


import mixin from './mixin'
import MyCurrentOrder from './MyOrder/main';
import MyHistoryOrder from './MyOrder/History/main';
import BuySellPan from './BuySellPan/main';
import LiveTrade from './LiveTrade/main';
import tpl from "./tpl.html";
import util from './util';
import SuperKline from '../../component/SuperKline.vue'
import SimpleKline from '../../../grsc-base/component/SimpleKline.vue';
import TimeShare from '../../../grsc-base/component/TimeShare.vue';
import Depth from '../../../grsc-base/component/Depth/Depth.vue';

const ORDER_CURRENT = 'current';
const ORDER_HISTORY = 'history';

export default Vue.extend({
    name: "Market",
    template: tpl,
    mixins: [mixin],
    components: {
        Validator,
        MyCurrentOrder,
        MyHistoryOrder,
        BuySellPan,
        LiveTrade,
        SuperKline,
        SimpleKline,
        Depth,
        TimeShare
    },
    data() {
        let coin = this.$$symbol.split('_')[1];
        let coinText = coin;
        if (coin === 'TIC') {
            coinText = 'TV';
        }

        return {
            ORDER_CURRENT,
            ORDER_HISTORY,
            orderType: ORDER_CURRENT,
            chartType: 'superkline',
            hasReadyShowSuperKline: false,
            height: 400,
            hasLogin: false,
            priceType: true,
            amountLocking:'',
            amountLockingAvailable:'',
            acount: false,
            surplus: 0,
            lockingDetail1:0,
            lockingDetail2:0,
            lockingDetail3:0,
            lockingDetail4:0,
            lockingDetail5:0,
            buyRules: {
                price: {
                    required: true,
                    requiredTip: this.$t('trade.buyRullPriceTip'),
                },
                amount: {
                    tip: this.$t('trade.maxBuy') + '：-- ' + coinText,
                    required: true,
                    requiredTip: this.$t('trade.buyRullAmountTip'),
                }
            },
            sellRules: {
                price: {
                    required: true,
                    requiredTip: this.$t('trade.sellRullPriceTip'),
                },
                amount: {
                    tip: this.$t('trade.maxSell') + '：-- ' + coinText,
                    required: true,
                    requiredTip: this.$t('trade.sellRullAmountTip'),
                }
            },
            price_tabs: {
                price1: {

                },
                // price2: {

                // },
                price3: {

                },
            },
            coin: coin,
            coinText: coinText
        };
    },

    created() {
        $(document).off('$$assets.updateAssets').on('$$assets.updateAssets', () => {
            this._fetchTotalAssets();
        });
        this.remainingNumber();
        this.getSymbolLockingDetail();
        let regions = JSON.parse(localStorage.getItem("regions"));
        $.map(regions, (item, key) => {
            if (item === this.$$symbol) {
                this.acount = true;
            }
        });
        // if(this.$$symbol=='USDT_DFP'){
        //     this.acount = true;
        // }
        localStorage.setItem('coinT',this.coinText);
    },

    mounted() {
        let dom = this.$refs.layoutMiddle;
        dom.style.height = commonUtil.getMdHeight() + 'px';
        this.height = commonUtil.getMdHeight();

        this.hasReadyShowSuperKline = true;

        $(window).resize(() => {
            dom.style.height = commonUtil.getMdHeight() + 'px';
            this.height = commonUtil.getMdHeight();
        });
    },
    watch: {
        /**
         * 最大可卖数量
         * @param newVal
         * @param oldVal
         */
        coinBalance(newVal, oldVal) {
            let tip = this.$t('trade.maxSell') + '：' + newVal + ' ' + this.coinText;
            this.sellRules.amount.tip = tip;
            this.sellRules.amount.max = newVal;
            this.sellRules.amount.maxTip = tip;
            this.sellRules.amount.$setRight(tip);
        },
        /**
         * 买入价格发生变化, 最大可买数量也会发生变化
         * @param newVal
         * @param oldVal
         */
        'buyForm.price'(newVal, oldVal) {
            let tip = '';
            if (newVal !== '' && +newVal !== 0) {
                let maxCoin = util.getMaxCoin(this.currencyBalance, newVal, 1, this.coinText);
                tip = this.$t('trade.maxBuy') + '：' + maxCoin + ' ' + this.coinText;
                this.buyRules.amount.tip = tip;
                this.buyRules.amount.max = maxCoin;
                this.buyRules.amount.maxTip = tip;
                this.buyRules.amount.$setRight(this.buyRules.amount.tip);
            } else {
                tip = this.$t('trade.maxBuy') + '：-- ' + this.coinText;
                this.buyRules.amount.tip = tip;
                this.buyRules.amount.max = '--';
                this.buyRules.amount.maxTip = tip;
                this.buyRules.amount.$setRight(tip);
            }
            this.buyPercent = '';
        }
    },
    methods: {
        _fetchTotalAssets() {
            this.isRequesting = true;
            commonService.getTotalAssets().done(rep => {
                if (rep.code === window.CODE.SUCCESS) {
                    this.hasLogin = true;
                    this.isRequesting = false;
                    rep.data.forEach(item => {
                        console.log(this.$$sellNumber)
                        switch (item.assetCode) {
                            case this.coinText:
                                this.amountLocking = item.amountLocking;
                                this.amountLockingAvailable = item.amountLockingAvailable;
                                if (item.assetCode === 'BTC') {
                                    this.coinBalance = filter.floorFix((filter.floorFix(item.amountAvailable, 10)), 8);
                                } else {
                                    this.coinBalance = filter.floorFix(item.amountAvailable, this.$$amountPrecision);
                                }
                                this.coinBalanceLock = item.amountLock;
                                break;
                            case this.$$symbol.split('_')[0]:
                                if (item.assetCode === 'USC' || item.assetCode === 'USDT') {
                                    this.currencyBalance = filter.floorFix(item.amountAvailable, this.$$coinPrecision);
                                } else {
                                    this.currencyBalance = filter.floorFix((filter.floorFix(item.amountAvailable, 10)), 8);
                                }
                                break;
                        }
                    });

                } else if (rep.code === window.CODE.NO_LOGIN.CODE) {
                    this.hasLogin = false;
                } else {
                    window.error(rep.msg);
                }
            });
        },

         //判断是否免密支付1
         noPassword1() {
            let param = {
                orderNo: commonUtil.getUuid(),
                symbol: this.$$symbol
            };
            let header = {
                'pay-password': ' '
            };
            service.match(param, header).done(rep => {
                if (rep.code === window.CODE.SUCCESS) {
                    window.success('成功')
                    setTimeout(() => {
                        this.getSymbolLockingDetail();
                        this._fetchTotalAssets();
                        this.remainingNumber();
                    }, 1500);
                } else {
                    window.error(rep.msg);
                }

            }).always(() => {

            });
        },

        remainingNumber() {
            commonService.remainingNumber({
                symbol:this.$$symbol
            }).done(rep => {
                if (rep.code === window.CODE.SUCCESS) {
                    this.surplus = rep.data;
                }
            })
        },

        getSymbolLockingDetail() {
            let assets = this.$$symbol.split('_');
            commonService.getSymbolInnovationl({
                assetCode:assets[1]
            }).done(rep => {
                if (rep.code === window.CODE.SUCCESS) {
                    this.lockingDetail1 = rep.data.amountLocking;
                    this.lockingDetail2 = rep.data.yesterdayUnlockAmount;
                    this.lockingDetail3 = rep.data.totalUnlockAmount;
                    this.lockingDetail4 = rep.data.yesterdayRewardAmount;
                    this.lockingDetail5 = rep.data.totalRewardAmount;
                }
            })
        },

        /**
         * 设置买/卖类型
         * @param type
         */
        setOrderType(type) {
            this.orderType = type;
        },

        /**
                 * 设置限价/行情价类型
                 * @param type
                 */
        changePrice1() {
            this.priceType = true
        },
        changePrice2() {
            this.priceType = false
        },

        /**
         * 设置图表类型 深度图，k线图
         * @param type
         */
        setChartType(type) {
            this.chartType = type
        }
    }
})